package com.qf.hospital.controller;

import com.github.pagehelper.PageInfo;
import com.qf.hospital.entity.SysMenu;
import com.qf.hospital.service.SysMenuService;
import com.qf.hospital.vo.LayUIDTreeVO;
import com.qf.hospital.vo.R;
import com.qf.hospital.vo.SysMenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zjw
 * @description  菜单管理Controller
 * @date 2021/10/19 11:27
 */
@RestController
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询左侧的树结构
     * @param spread
     * @return
     */
    @PostMapping("/sel/loadMenuMangerLeftTreeJson")
    public R loadMenuMangerLeftTreeJson(Integer spread){
        // 将spread当做标识，如果传递了spread，只查询一级和二级菜单返回结果，应用于添加&修改
        //1. 调用Service查询菜单信息
        List<SysMenu> sysMenuList = sysMenuService.findAll();
        //2. 封装数据
        List<LayUIDTreeVO> data = new ArrayList<>();
        if(spread != null){
            for (SysMenu sysMenu : sysMenuList) {
                if (sysMenu.getParentId() == 0 || sysMenu.getParentId() == 1) {
                    LayUIDTreeVO vo = new LayUIDTreeVO();
                    BeanUtils.copyProperties(sysMenu, vo);
                    data.add(vo);
                }
            }
        }else {
            for (SysMenu sysMenu : sysMenuList) {
                LayUIDTreeVO vo = new LayUIDTreeVO();
                BeanUtils.copyProperties(sysMenu, vo);
                data.add(vo);
            }
        }
        //3. 返回
        return R.ok(data);
    }


    /**
     * 展示table数据
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/sel/queryMenuAllList")
    public R queryMenuAllList(String title,
                              @RequestParam(defaultValue = "1")Integer page,
                              @RequestParam(defaultValue = "10")Integer limit){
        //1. 调用Service查询
        PageInfo<SysMenu> pageInfo = sysMenuService.findByTitle(title,page,limit);

        //2. 封装数据
        long count = pageInfo.getTotal();
        List<SysMenuVO> data = new ArrayList<>();
        for (SysMenu sysMenu : pageInfo.getList()) {
            SysMenuVO vo = new SysMenuVO();
            BeanUtils.copyProperties(sysMenu,vo);
            data.add(vo);
        }

        //3. 返回
        return R.ok(count,data);
    }
}
